package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @PostMapping
    public R<String> add(@RequestBody DishDto dishDto) {
        dishService.saveDishFlavor(dishDto);
        return R.success("添加成功!");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    @Cacheable(value = "dishCache",key = "#page+'_'+#pageSize")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Dish> p = new Page<>(page, pageSize);
        Page<DishDto> dtoPage = new Page<>();
        LambdaQueryWrapper<Dish> lam = new LambdaQueryWrapper<>();
        lam.like(name != null, Dish::getName, name);
        //分页查询,将数据查询到 p中
        dishService.page(p, lam);
        //将除了数据以外的杂数据拷贝到dto中
        BeanUtils.copyProperties(p, dtoPage, "records");
        List<DishDto> collect = p.getRecords().stream().map((s) -> {
            //创建dto对象用于接收dish的数据
            DishDto dto = new DishDto();
            Long categoryId = s.getCategoryId();
            String categoryName = categoryService.getById(categoryId).getName();
            BeanUtils.copyProperties(s, dto);
            //获取菜品名称,将它存入dto中
            dto.setCategoryName(categoryName);
            //收集所有dto
            return dto;
        }).collect(Collectors.toList());
        //将所有dto数据存入
        dtoPage.setRecords(collect);
        //返回数据
        return R.success(dtoPage);
    }

    /**
     * 菜品编辑的数据回显
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @Cacheable(value = "dishCache",key = "#id")
    public R<DishDto> show(@PathVariable Long id) {

        Dish dish = dishService.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        LambdaQueryWrapper<DishFlavor> lam = new LambdaQueryWrapper<>();
        lam.eq(DishFlavor::getDishId, id);
        List<DishFlavor> list = dishFlavorService.list(lam);
        dishDto.setFlavors(list);

        return R.success(dishDto);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> update(@RequestBody DishDto dishDto) {
        LambdaQueryWrapper<DishFlavor> lam = new LambdaQueryWrapper<>();
        lam.eq(DishFlavor::getDishId, dishDto.getId());
        //为了避免繁琐的判断,先将菜品的口味全部删除,再进行批量添加
        List<DishFlavor> list = dishFlavorService.list(lam);
        //判断需删除的菜品有没有口味,有才进行删除
        if (list!=null){
        dishFlavorService.remove(lam);
        }
        List<DishFlavor> flavors = dishDto.getFlavors();
        List<DishFlavor> collect = flavors.stream().map(item -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        //判断前端口味是否为空
        if (dishDto.getFlavors()!=null){
        dishFlavorService.saveBatch(collect);
        }
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDto, dish,"flavors");
        dishService.updateById(dish);
        return R.success("修改成功!");

    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> deleteById(Long[] ids) {
        //删除口味
        for (Long id : ids) {
            LambdaQueryWrapper<DishFlavor> lam = new LambdaQueryWrapper<>();
            lam.eq(DishFlavor::getDishId, id);
            dishFlavorService.remove(lam);
            //删除菜品
            dishService.removeById(id);
        }
        return R.success("ok");
    }

    /**
     * 批量修改菜品状态
     *
     * @param statusId
     * @param ids
     * @return
     */
    @CacheEvict(value = "dishCache",allEntries = true)
    @PostMapping("/status/{statusId}")
    public R<String> updateStatus(@PathVariable int statusId, Long[] ids) {
        List<Dish> list = new ArrayList<>();
        for (Long id : ids) {
            Dish byId = dishService.getById(id);
            list.add(byId);
        }
        List<Dish> collect = list.stream().map((d) -> {
            d.setStatus(statusId);
            return d;
        }).collect(Collectors.toList());
        dishService.updateBatchById(collect);
        return R.success("修改成功!");
    }


    @GetMapping("/list")
    @Cacheable(value = "dishCache",key = "#dish.categoryId+'_'+#dish.status")
    public R<List<DishDto>> listR( Dish dish) {
        List<DishDto> list = dishService.getList(dish);

        return R.success(list);
    }
//@GetMapping("/list")
//public R<List<DishDto>> list(Dish dish){
//    //构造查询条件
//    LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//    queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
//    //添加条件，查询状态为1（起售状态）的菜品
//    queryWrapper.eq(Dish::getStatus,1);
//    //添加排序条件
//    queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//
//    List<Dish> list = dishService.list(queryWrapper);
//
//    List<DishDto> dishDtoList = list.stream().map((item) -> {
//        DishDto dishDto = new DishDto();
//        BeanUtils.copyProperties(item,dishDto);
//
//        Long categoryId = item.getCategoryId();//分类id
//        //根据id查询分类对象
//        Category category = categoryService.getById(categoryId);
//        if(category != null){
//            String categoryName = category.getName();
//            dishDto.setCategoryName(categoryName);
//        }
//
//        //当前菜品的id
//        Long dishId = item.getId();
//        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
//        //SQL:select * from dish_flavor where dish_id = ?
//        List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
//        dishDto.setFlavors(dishFlavorList);
//
//        return dishDto;
//    }).collect(Collectors.toList());
//
//    return R.success(dishDtoList);
//}


}



